#include <QHostAddress>
#include <QNetworkInterface>
#include <QMessageBox>
#include "createsession.h"
#include "ui_createsession.h"
#include "constants.h"
#include "Preferences/preferences.h"


CreateSession::CreateSession(QWidget *parent) : QDialog(parent), ui(new Ui::CreateSession)
{
	pushButton_textColour = new ColourButton(this);

	ui->setupUi(this);

	//load the username and colour from preferences
	ui->lineEdit_user->setText(Preferences::getInstance()->getValue(Preferences::SETTING_DEFAULT_NAME).toString());
	pushButton_textColour->setColour(Preferences::getInstance()->getValue(Preferences::SETTING_DEFAULT_TEXT_COLOUR).value<QColor>());

	ui->lineEdit_session->setText(ui->lineEdit_user->text() + "'s Session");

	//figure out the host ip (or guess a nice-ish one)	
	QString host = "127.0.0.1";
	QList<QHostAddress> interfaceList = QNetworkInterface::allAddresses();

	for (int i = 1; i < interfaceList.length(); i++)
	{
		if (interfaceList.at(i).protocol() == QAbstractSocket::IPv4Protocol)
		{
			host = interfaceList.at(i).toString();
			break;
		}
	}

	ui->label_IP->setText(host);
	ui->label_port->setText(QString::number(DEFAULT_PORT));
	ui->gridLayout_userInfo->addWidget(pushButton_textColour, 2, 2);

	ui->lineEdit_session->setFocus();
}

CreateSession::~CreateSession()
{
	delete ui;
	ui = NULL;
}

NewFile::DocumentType CreateSession::getDocumentType() const
{
	if (ui->radioButton_textDocument->isChecked())
		return NewFile::DOCUMENT_TEXT;

	else if (ui->radioButton_formattedDocument->isChecked())
		return NewFile::DOCUMENT_FORMATTED;

	else
		return NewFile::DOCUMENT_NONE;
}

QString CreateSession::getSessionName()
{
	return ui->lineEdit_session->text();
}

int CreateSession::getPort()
{
	return DEFAULT_PORT;
}

QString CreateSession::getUserName()
{
	return (ui->lineEdit_user->text());
}

QColor CreateSession::getUserColour()
{
	return (pushButton_textColour->getColour());
}

void CreateSession::accept()
{
	if (ui->lineEdit_session->text().isEmpty())
	{
		QMessageBox::warning(this, "Invalid Session Information",
				     "A valid session name is required to create "
				     "a new session");

		ui->lineEdit_session->setFocus();
	}
	else if (ui->lineEdit_user->text().isEmpty())
	{
		QMessageBox::warning(this, "Invalid User Information",
				     "A valid user name is required to create a new session");

		ui->lineEdit_user->setFocus();
	}
	else
	{
		//save the username and text colour
		Preferences::getInstance()->setValue(Preferences::SETTING_DEFAULT_NAME, ui->lineEdit_user->text());
		Preferences::getInstance()->setValue(Preferences::SETTING_DEFAULT_TEXT_COLOUR, pushButton_textColour->getColour());

		QDialog::accept();
	}
}

void CreateSession::changeEvent(QEvent *e)
{
	QDialog::changeEvent(e);

	switch (e->type())
	{
		case QEvent::LanguageChange:
			ui->retranslateUi(this);

			break;

		default:
			break;
	}
}
